﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TbShop.Web.Infrastructure.FromExtend
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateReHttpPostTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public IPageTokenView PageTokenView { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateReHttpPostTokenAttribute"/> class.
        /// </summary> 
        public ValidateReHttpPostTokenAttribute(string key = "default")
        {
            //It would be better use DI inject it.
            PageTokenView = new SessionPageTokenView(key);
        }

        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new CustomerException.ArgumentException("参数不可为空！");
            }
            if (!PageTokenView.TokensMatch)
            {
                throw new CustomerException.PostException("该表单已提交完成，请不要重复提交！");
            }
        }
    }
}